<template>
  <el-cascader
    v-model="selectedRegion"
    :options="regionOptions"
    :props="cascaderProps"
    clearable
    filterable
    placeholder="请选择省市区"
    style="width: 100%;"
    @change="handleChange"
  ></el-cascader>
</template>

<script>
import regionData from '@/utils/regionData';

export default {
  name: 'RegionCascader',
  props: {
    value: {
      type: [String, Array],
      default: ''
    },
    multiple: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      regionOptions: regionData,
      selectedRegion: []
    };
  },
  computed: {
    cascaderProps() {
      return {
        value: 'value',
        label: 'label',
        children: 'children',
        expandTrigger: 'hover',
        checkStrictly: false,
        multiple: this.multiple  // 使用 this.multiple
      };
    }
  },
  watch: {
    value: {
      immediate: true,
      handler(newVal) {
        if (newVal) {
          if (Array.isArray(newVal)) {
            this.selectedRegion = newVal;
          } else if (typeof newVal === 'string') {
            // 如果是字符串格式，尝试解析
            try {
              this.selectedRegion = JSON.parse(newVal);
            } catch (e) {
              // 如果不是JSON格式，可能是逗号分隔的字符串
              this.selectedRegion = newVal.split(',').filter(item => item);
            }
          }
        } else {
          this.selectedRegion = [];
        }
      }
    }
  },
  methods: {
    handleChange(value) {
      if (value && value.length > 0) {
        // 返回选中的地区编码数组
        this.$emit('input', value);
        // 同时返回完整信息，方便父组件使用
        this.$emit('change', {
          codes: value,
          names: this.getSelectedRegionNames(value),
          fullName: this.getFullRegionName(value)
        });
      } else {
        this.$emit('input', []);
        this.$emit('change', {
          codes: [],
          names: [],
          fullName: ''
        });
      }
    },
    
    // 获取选中的地区名称
    getSelectedRegionNames(codes) {
      const names = [];
      let currentLevel = this.regionOptions;
      
      for (let i = 0; i < codes.length; i++) {
        const code = codes[i];
        const region = currentLevel.find(item => item.value === code);
        if (region) {
          names.push(region.label);
          currentLevel = region.children || [];
        } else {
          names.push('');
        }
      }
      
      return names;
    },
    
    // 获取完整的地区名称（如：广东省-广州市-天河区）
    getFullRegionName(codes) {
      const names = this.getSelectedRegionNames(codes);
      return names.join('-');
    },
    
    // 根据编码获取地区信息
    getRegionByCode(code) {
      return this.findRegionInTree(this.regionOptions, code);
    },
    
    findRegionInTree(tree, code) {
      for (const region of tree) {
        if (region.value === code) {
          return region;
        }
        if (region.children) {
          const found = this.findRegionInTree(region.children, code);
          if (found) return found;
        }
      }
      return null;
    }
  }
};
</script>